package com.ld.task;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch:放行条件由第三者控制。
 */
public class UseCountDownLatch {
    //创建CountDownLatch实例,初始化计数器的值
    static CountDownLatch countDownLatch = new CountDownLatch(6);

    static class BeforeWork implements Runnable {
        @Override
        public void run() {
            System.out.println("Thread " + Thread.currentThread().getName() + " 开始准备工作...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread " + Thread.currentThread().getName() + " 准备工作完成...");
            countDownLatch.countDown();
        }
    }

    static class WorkTask implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("工作线程等待准备工作的线程执行完成...");
                countDownLatch.await();//等待计数器的值变为0,继续向下执行
                System.out.println("工作线程 Thread" + Thread.currentThread().getName() + "开始工作...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main线程开始工作...");
        new Thread(new WorkTask()).start();
        for (int i = 0; i < 4; i++) {
            new Thread(new BeforeWork()).start();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "线程准备工作第一步...");
                    Thread.sleep(1000);
                    countDownLatch.countDown();
                    System.out.println(Thread.currentThread().getName() + "线程准备工作第二步...");
                    Thread.sleep(1000);
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        countDownLatch.await();
        System.out.println("23123123123213");
    }
}
